﻿using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Reactive.Linq;
using Caliburn.Micro;
using WP7Contrib.Common.Extensions;
using Wulong.Phone.Qiushi.Models;
using Wulong.Phone.Utils;

namespace Wulong.Phone.Qiushi.ViewModels
{
    public class QiushiListViewModelStorage : StorageHandler<QiushiListViewModel>
    {
        public override void Configure()
        {
            //Id(x=>x.Section);
            //Property(x => x.QiushiItems).InAppSettings();
            Property(x => x.Section).InPhoneState().RestoreAfterViewReady();
            Property(x => x.CanLoadMore).InPhoneState().RestoreAfterViewReady();
            //Property(x => x.QiushiItemRestored).InAppSettings().RestoreAfterViewReady();
            //Property(x => x.IsBusy).InAppSettings();
            //Property(x => x.Page).InAppSettings();
            //Property(x => x.QiushiItemRestored).InAppSettings().Configure(x =>
            //                                                           {
            //                                                               x.Save = SaveStrokes;
            //                                                               x.Restore = RestoreStrokes;
            //                                                           }).RestoreAfterViewReady();
        }

        void SaveStrokes(QiushiListViewModel vm, Func<string> serialize, StorageMode nMode)
        {
            IsolatedStorageHelper.SaveObject(vm.Section, vm.QiushiItemRestored);
        }

        void RestoreStrokes(QiushiListViewModel vm, Func<string> serialize, StorageMode nMode)
        {
            // use IsolatedStorageSettings.ApplicationSettings[vm.DisplayName + "ThePropertyKey"] 
            // to check if the key exists, and if it is there get the serialized data and deserialize
            if (vm.Section == null)
                return;
            if (IsolatedStorageSettings.ApplicationSettings[vm.Section] != null)
            {
                IsolatedStorageHelper.GetObject<IEnumerable<QiushiItem>>(vm.Section)
                                        .ObserveOnDispatcher()
                    .Subscribe(x =>
                                   {
                                       vm.QiushiItemRestored.AddRange(x);
                                       
                                   });
                
            }
        }

    }
}
